﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Data;
using System.Drawing;
using Infragistics.WebUI.UltraWebGrid;

public partial class ScrapPopupForm : System.Web.UI.Page
{
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESRejectAppBusiness rejectapp = new uMESRejectAppBusiness();

    string businessName = "质量管理", parentName = "scrapinfo";
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            Dictionary<string, object> popupData = (Dictionary<string, object>)Session["PopupData"];
            txtDispContainerID.Text = popupData["ContainerID"].ToString();
            txtDispProcessNo.Text = popupData["ProcessNo"].ToString();
            txtDispOprNo.Text = popupData["OprNo"].ToString();
            txtDispContainerName.Text = popupData["ContainerName"].ToString();
            txtDispProductName.Text = popupData["ProductName"].ToString();
            txtDispDescription.Text = popupData["Description"].ToString();
            txtDispContainerQty.Text = popupData["ContainerQty".ToString()].ToString();
            txtDispSpecID.Text = popupData["SpecID"].ToString();
            txtDispPlannedStartDate.Text = popupData["PlannedStartDate"].ToString();
            txtDispPlannedCompletionDate.Text = popupData["PlannedCompletionDate"].ToString();
            txtID.Text = popupData["ID"].ToString();
            txtDispWorkflowID.Text = popupData["WorkflowID"].ToString();
            txtDispWorkReportID.Text = popupData["WorkReportID"].ToString();
            txtQty.Text = popupData["Qty"].ToString();
            txtSpecName.Text = popupData["SpecName"].ToString();

            string strPageName = popupData["PageName"].ToString();
            txtPageName.Text = strPageName;
            string strChildCount = popupData["ChildCount"].ToString();
            txtChildCount.Text = strChildCount;

            if (strPageName == "RejectCheckDispose")
            {
                DataTable dtProductNo = (DataTable)(popupData["dtProductNo"]);
                wgProductNoList.DataSource = dtProductNo;
                wgProductNoList.DataBind();
            }
            else if (strPageName == "ContainerCheck")
            {
                wgProductNoList.Columns.FromKey("LossReasonName").Hidden = true;
                wgProductNoList.Columns.FromKey("LossReason").Hidden = false;
                wgProductNoList.Columns.FromKey("DisposeResult").Hidden = true;

                if (strChildCount == "0")
                {
                    wgProductNoList.Columns.FromKey("ProductNo").Hidden = true;
                    wgProductNoList.Columns.FromKey("Qty").AllowUpdate = AllowUpdate.Yes;
                    btnAdd.Visible = true;
                    btnDel.Visible = true;
                }
                else
                {
                    DataTable dtProductNo = (DataTable)(popupData["dtProductNo"]);
                    wgProductNoList.DataSource = dtProductNo;
                    wgProductNoList.DataBind();
                }
            }

            Session["PopupData"] = null;

            txtScrapInfoName.Text = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            GetFactory();
            GetLossReason();
        }
    }

    #region 获取车间
    protected void GetFactory()
    {
        DataTable DT = common.GetFactoryNames();

        ddlFactory.DataTextField = "FactoryName";
        ddlFactory.DataValueField = "FactoryID";
        ddlFactory.DataSource = DT;
        ddlFactory.DataBind();

        ddlFactory.Items.Insert(0, string.Empty);
    }
    #endregion

    #region 获取人员
    protected void GetEmployee()
    {
        string strFactoryID = ddlFactory.SelectedValue;
        DataTable DT = common.GetEmployeeByFactory(strFactoryID);

        ddlEmployee.DataTextField = "FullName";
        ddlEmployee.DataValueField = "EmployeeID";
        ddlEmployee.DataSource = DT;
        ddlEmployee.DataBind();

        ddlEmployee.Items.Insert(0, "");
    }
    #endregion

    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        lStatusMessage.Text = strMessage;

        if (boolResult == true)
        {
            lStatusMessage.ForeColor = Color.Black;
        }
        else
        {
            lStatusMessage.ForeColor = Color.Red;
        }
    }
    #endregion

    #region 提交按钮
    protected void btnMaterialApp_Click(object sender, EventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            string strFactoryID = ddlFactory.SelectedValue;
            if (strFactoryID == string.Empty)
            {
                ShowStatusMessage("请选择责任部门", false);
                return;
            }

            int intQty = 0;
            DataTable DT = new DataTable();
            DT.Columns.Add("ID");
            DT.Columns.Add("ContainerID");
            DT.Columns.Add("ContainerName");
            DT.Columns.Add("ProductNo");
            DT.Columns.Add("Qty");
            DT.Columns.Add("UOMID");
            DT.Columns.Add("LossReasonID");
            DT.Columns.Add("LossReasonName");
            DT.Columns.Add("Notes");

            TemplatedColumn temCell1 = (TemplatedColumn)wgProductNoList.Columns.FromKey("ckSelect");
            TemplatedColumn temCell2 = (TemplatedColumn)wgProductNoList.Columns.FromKey("LossReason");

            string strPageName = txtPageName.Text;
            string strChildCount = txtChildCount.Text;

            if ((strPageName == "ContainerCheck" && strChildCount != "0") || strPageName == "RejectCheckDispose")
            {
                for (int i = 0; i < temCell1.CellItems.Count; i++)
                {
                    Infragistics.WebUI.UltraWebGrid.CellItem cellItem1 = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell1.CellItems[i];
                    CheckBox ckSelect = (CheckBox)cellItem1.FindControl("ckSelect");
                    Infragistics.WebUI.UltraWebGrid.CellItem cellItem2 = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell2.CellItems[i];
                    DropDownList ddlLossReason = (DropDownList)cellItem2.FindControl("ddlLossReason");

                    if (ckSelect.Checked == true)
                    {
                        intQty += Convert.ToInt32(wgProductNoList.Rows[i].Cells.FromKey("Qty").Value.ToString());

                        DataRow row = DT.NewRow();

                        if (wgProductNoList.Rows[i].Cells.FromKey("ID").Value != null)
                        {
                            row["ID"] = wgProductNoList.Rows[i].Cells.FromKey("ID").Value.ToString();
                        }
                        else
                        {
                            row["ID"] = string.Empty;
                        }

                        if (wgProductNoList.Rows[i].Cells.FromKey("ContainerID").Value != null)
                        {
                            row["ContainerID"] = wgProductNoList.Rows[i].Cells.FromKey("ContainerID").Value.ToString();
                        }
                        else
                        {
                            row["ContainerID"] = string.Empty;
                        }

                        if (wgProductNoList.Rows[i].Cells.FromKey("ContainerName").Value != null)
                        {
                            row["ContainerName"] = wgProductNoList.Rows[i].Cells.FromKey("ContainerName").Value.ToString();
                        }
                        else
                        {
                            row["ContainerName"] = string.Empty;
                        }

                        if (wgProductNoList.Rows[i].Cells.FromKey("ProductNo").Value != null)
                        {
                            row["ProductNo"] = wgProductNoList.Rows[i].Cells.FromKey("ProductNo").Value.ToString();
                        }
                        else
                        {
                            row["ProductNo"] = string.Empty;
                        }

                        row["Qty"] = wgProductNoList.Rows[i].Cells.FromKey("Qty").Value.ToString();
                        row["UOMID"] = string.Empty;

                        if (!string.IsNullOrWhiteSpace(wgProductNoList.Rows[i].Cells.FromKey("LossReasonID").Text))
                        {
                            row["LossReasonID"] = wgProductNoList.Rows[i].Cells.FromKey("LossReasonID").Value.ToString();
                        }
                        else
                        {
                            if (ddlLossReason.SelectedValue == string.Empty)
                            {
                                ShowStatusMessage("请选择报废原因", false);
                                return;
                            }
                            else
                            {
                                row["LossReasonID"] = ddlLossReason.SelectedValue;
                            }
                        }

                        if (!string.IsNullOrWhiteSpace(wgProductNoList.Rows[i].Cells.FromKey("LossReasonName").Text) )
                        {
                            row["LossReasonName"] = wgProductNoList.Rows[i].Cells.FromKey("LossReasonName").Value.ToString();
                        }
                        else
                        {
                            if (ddlLossReason.SelectedValue == string.Empty)
                            {
                                ShowStatusMessage("请选择报废原因", false);
                                return;
                            }
                            else
                            {
                                row["LossReasonName"] = ddlLossReason.SelectedItem.Text;
                            }
                        }

                        row["Notes"] = string.Empty;

                        DT.Rows.Add(row);
                    }
                }
            }
            else if (strPageName == "ContainerCheck" && strChildCount == "0")
            {
                for (int i = 0; i < temCell1.CellItems.Count; i++)
                {
                    Infragistics.WebUI.UltraWebGrid.CellItem cellItem2 = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell2.CellItems[i];
                    DropDownList ddlLossReason = (DropDownList)cellItem2.FindControl("ddlLossReason");

                    intQty += Convert.ToInt32(wgProductNoList.Rows[i].Cells.FromKey("Qty").Value.ToString());

                    DataRow row = DT.NewRow();

                    if (wgProductNoList.Rows[i].Cells.FromKey("ID").Value != null)
                    {
                        row["ID"] = wgProductNoList.Rows[i].Cells.FromKey("ID").Value.ToString();
                    }
                    else
                    {
                        row["ID"] = string.Empty;
                    }

                    if (wgProductNoList.Rows[i].Cells.FromKey("ContainerID").Value != null)
                    {
                        row["ContainerID"] = wgProductNoList.Rows[i].Cells.FromKey("ContainerID").Value.ToString();
                    }
                    else
                    {
                        row["ContainerID"] = string.Empty;
                    }

                    if (wgProductNoList.Rows[i].Cells.FromKey("ContainerName").Value != null)
                    {
                        row["ContainerName"] = wgProductNoList.Rows[i].Cells.FromKey("ContainerName").Value.ToString();
                    }
                    else
                    {
                        row["ContainerName"] = string.Empty;
                    }

                    if (wgProductNoList.Rows[i].Cells.FromKey("ProductNo").Value != null)
                    {
                        row["ProductNo"] = wgProductNoList.Rows[i].Cells.FromKey("ProductNo").Value.ToString();
                    }
                    else
                    {
                        row["ProductNo"] = string.Empty;
                    }

                    row["Qty"] = wgProductNoList.Rows[i].Cells.FromKey("Qty").Value.ToString();
                    row["UOMID"] = string.Empty;

                    if (ddlLossReason.SelectedValue == string.Empty)
                    {
                        ShowStatusMessage("请选择报废原因", false);
                        return;
                    }
                    else
                    {
                        row["LossReasonID"] = ddlLossReason.SelectedValue;
                    }

                    if (ddlLossReason.SelectedValue == string.Empty)
                    {
                        ShowStatusMessage("请选择报废原因", false);
                        return;
                    }
                    else
                    {
                        row["LossReasonName"] = ddlLossReason.SelectedItem.Text;
                    }

                    row["Notes"] = string.Empty;

                    DT.Rows.Add(row);
                }

                if (intQty > Convert.ToInt32(txtQty.Text))
                {
                    ShowStatusMessage("总报废数量不能大于报工数量", false);
                    return;
                }
            }

            if (intQty == 0)
            {
                ShowStatusMessage("请选择报废的产品序号或输入报废数量", false);
                return;
            }

            string strScrapInfoName = txtScrapInfoName.Text;
            string strContainerID = txtDispContainerID.Text;
            string strSpecID = txtDispSpecID.Text;
            string strRejectAppInfoID = txtID.Text;
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            string strSubmitEmployeeID = userInfo["EmployeeID"];
            string strEmployeeID = ddlEmployee.SelectedValue;
            string strQualityNotes = txtNotes.Text.Trim();
            
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("ScrapInfoName", strScrapInfoName);
            para.Add("ContainerID", strContainerID);
            para.Add("SpecID", strSpecID);
            para.Add("RejectAppInfoID", strRejectAppInfoID);
            para.Add("Qty", intQty.ToString());
            para.Add("SubmitEmployeeID", strSubmitEmployeeID);
            para.Add("SubmitDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            para.Add("FactoryID", userInfo["FactoryID"]);
            para.Add("EmployeeID", userInfo["EmployeeID"]);
            para.Add("Notes", txtNotes.Text.Trim());

            //增加工艺规程ID
            para.Add("WorkflowID", txtDispWorkflowID.Text.Trim());
            para.Add("ScrapInfoID", Guid.NewGuid().ToString());//
         

            //执行ChangeQty-Loss
            string strEmployeeName = userInfo["ApiEmployeeName"].ToString();
            string strPassword = userInfo["ApiPassword"].ToString();

            if (strChildCount == "0")
            {
                //para = new Dictionary<string, string>(); update:Wangjh 20201209 注释，否则后续插入报废单会报错
                para.Add("ContainerName", txtDispContainerName.Text);
                para.Add("Level", "Lot");
                para.Add("ServerUser", strEmployeeName);
                para.Add("ServerPassword", strPassword);

                DataTable dtChangeQtyDetails = new DataTable();
                dtChangeQtyDetails.Columns.Add("Qty");
                dtChangeQtyDetails.Columns.Add("ReasonCode");

                foreach (DataRow row in DT.Rows)
                {
                    DataRow r = dtChangeQtyDetails.NewRow();
                    r["Qty"] = row["Qty"].ToString();
                    r["ReasonCode"] = row["LossReasonName"].ToString();
                    dtChangeQtyDetails.Rows.Add(r);
                }

                string strInfo = string.Empty;
                Boolean result = rejectapp.ChangeQty(para, dtChangeQtyDetails, "Loss", out strInfo);
                if (result == true)
                {
                    rejectapp.AddScrapInfo(para, DT);
                    Response.Write("<script>parent.window.returnValue='1'; window.close()</script>");
                }
                else
                {
                    ShowStatusMessage(strInfo, result);
                    return;
                }

            }
            else
            {
                foreach (DataRow row in DT.Rows)
                {
                   var para1 = new Dictionary<string, string>();
                    para1.Add("ContainerName", row["ContainerName"].ToString());
                    para1.Add("Level", "Lot");
                    para1.Add("ServerUser", strEmployeeName);
                    para1.Add("ServerPassword", strPassword);

                    DataTable dtChangeQtyDetails = new DataTable();
                    dtChangeQtyDetails.Columns.Add("Qty");
                    dtChangeQtyDetails.Columns.Add("ReasonCode");

                    DataRow r = dtChangeQtyDetails.NewRow();
                    r["Qty"] = row["Qty"].ToString();
                    r["ReasonCode"] = row["LossReasonName"].ToString();
                    dtChangeQtyDetails.Rows.Add(r);

                    string strInfo = string.Empty;
                    Boolean result = rejectapp.ChangeQty(para1, dtChangeQtyDetails, "Loss", out strInfo);
                    if (result == true)
                    {
                        rejectapp.AddScrapInfo(para, DT);
                        Response.Write("<script>parent.window.returnValue='1'; window.close()</script>");
                    }
                    else
                    {
                        ShowStatusMessage(strInfo, result);
                        return;
                    }
                }
            }

            #region 记录日志
            var ml = new MESAuditLog();
            ml.ContainerName = txtDispContainerName.Text; ml.ContainerID = txtDispContainerID.Text;
            ml.ParentID = para["ScrapInfoID"]; ml.ParentName = parentName;
            ml.CreateEmployeeID = userInfo["EmployeeID"];
            ml.BusinessName = businessName; ml.OperationType = 0;
            ml.Description = string.Format("报废:" + txtSpecName.Text + ",报废数:{0}", para["Qty"]);
            common.SaveMESAuditLog(ml);
            #endregion


        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }
    #endregion

    protected void ddlFactory_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlEmployee.Items.Clear();

        if (ddlFactory.SelectedValue != string.Empty)
        {
            GetEmployee();
        }
    }

    #region 获取报废原因
    protected void GetLossReason()
    {
        DataTable DT = common.GetLossReason();
        Session["dtLossReason"] = DT;
    }
    #endregion

    //添加按钮
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            wgProductNoList.Rows.Add();
            wgProductNoList.Rows[wgProductNoList.Rows.Count - 1].Cells.FromKey("Qty").Value = "0";
            wgProductNoList.Rows[wgProductNoList.Rows.Count - 1].Cells.FromKey("DisposeResult").Value = "报废";

            TemplatedColumn temCell1 = (TemplatedColumn)wgProductNoList.Columns.FromKey("LossReason");
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem1 = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell1.CellItems[wgProductNoList.Rows.Count - 1];
            DropDownList ddlLossReason = (DropDownList)cellItem1.FindControl("ddlLossReason");

            ddlLossReason.DataTextField = "LossReasonName";
            ddlLossReason.DataValueField = "LossReasonID";
            ddlLossReason.DataSource = (DataTable)Session["dtLossReason"];
            ddlLossReason.DataBind();

            ddlLossReason.Items.Insert(0, string.Empty);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void wgProductNoList_DataBound(object sender, EventArgs e)
    {
        DataTable DT = (DataTable)Session["dtLossReason"];

        TemplatedColumn temCell1 = (TemplatedColumn)wgProductNoList.Columns.FromKey("LossReason");

        for (int i = 0; i < temCell1.CellItems.Count; i++)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem1 = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell1.CellItems[i];
            DropDownList ddlLossReason = (DropDownList)cellItem1.FindControl("ddlLossReason");

            ddlLossReason.DataTextField = "LossReasonName";
            ddlLossReason.DataValueField = "LossReasonID";
            ddlLossReason.DataSource = DT;
            ddlLossReason.DataBind();

            ddlLossReason.Items.Insert(0, "");
        }
    }

    protected void btnDel_Click(object sender, EventArgs e)
    {
        TemplatedColumn temCell1 = (TemplatedColumn)wgProductNoList.Columns.FromKey("ckSelect");

        for (int i = temCell1.CellItems.Count - 1; i >= 0; i--)
        {
            Infragistics.WebUI.UltraWebGrid.CellItem cellItem1 = (Infragistics.WebUI.UltraWebGrid.CellItem)temCell1.CellItems[i];
            CheckBox ckSelect = (CheckBox)cellItem1.FindControl("ckSelect");

            if (ckSelect.Checked == true)
            {
                wgProductNoList.Rows.RemoveAt(i);
            }
        }
    }
}